<template>
  <div>
    <div class="display-flex justify-content-flex-end">
      <div style="margin-left: 10px; margin-bottom: 10px">
        <el-button size="mini" type="primary" v-hasPermi="['technology:TechnologyWorkingAttach:add']" @click="openFunc" :disabled="status!==-1"
          >上传附件</el-button
        >
        <el-button size="mini" @click="handleDelete" v-hasPermi="['technology:TechnologyWorkingAttach:remove']" :disabled="status!==-1||single">删除附件</el-button>
      </div>
    </div>
    <el-table
      :cell-style="{ padding: this.tablePadding }"
      :data="list"
      height="145"
      border
      size="small"
      :span-method="listSpanMethod"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column
        label="附件类型"
        align="center"
        prop="attachType"
        :formatter="formatter"
      />
      <el-table-column label="附件名称" align="center" prop="name">
        <template slot-scope="scope">
          <el-link type="primary" :href="scope.row.url" target="_blank">{{
            scope.row.name
          }}</el-link>
        </template>
      </el-table-column>
      <el-table-column label="备注" align="center" prop="remark" />
      <el-table-column label="操作" align="center" min-width="120px">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            :disabled="status!==-1"
            @click="handleDelete(scope.row)"
            >删除</el-button
          >
          <el-button
            size="mini"
            type="text"
            icon="el-icon-download"
          
            ><el-link type="primary" :href="scope.row.url" target="_blank" style="font-size:12px;margin-top:-3px">下载</el-link></el-button
          >
        </template>
      </el-table-column>
    </el-table>
    <el-dialog :close-on-click-modal="false" :title="title" :visible.sync="open" width="630px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="120px">
        <el-form-item label="附件类型" prop="attachType">
          <div class="input-width">
            <el-select
              v-model="form.attachType"
              placeholder="请选择附件类型"
              clearable
              size="small"
            >
              <el-option
                v-for="dict in attachOptions"
                :key="dict.dictValue"
                :label="dict.dictLabel"
                :value="dict.dictValue"
              ></el-option>
            </el-select>
          </div>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input
            v-model="form.remark"
            placeholder="请输入备注"
            clearable
            size="small"
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>
        <el-form-item>
          <file-upload
            :value="fileValue"
            :isShowTip="true"
            :limit="1"
            :fileSize="0"
            :noResfileSize="false"
            btnTxt="点击上传附件"
            :fileType="fileType"
            @delFile="delFile"
            @setFile="setFile"
            ref="file"
          />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  technologyWorkingAttach,
  technologyWorkingAttachList,
  technologyWorkingAttachDel,
} from "@/api/technology/working";
import FileUpload from "@/components/FileUpload";
import { download } from "../../../../utils/download";
export default {
  props: ["id","status"],
  components: { FileUpload },
  data() {
    return {
      fileType: ["zip"],
      total: 0,
      multiple: false,
      ids: [],
      fileValue: [],
      open: false,
      title: "添加附件",
      list: [],
      queryParams: {
        workingId: "",
        pageNum: 1,
        pageSize: 100,
      },
      rules: {
        attachType: {
          required: true,
          message: "附件类型不能为空",
          trigger: "blur",
        },
      },
      form: {
        attachType: "",
      },
      attachOptions: [],
      spanData: [],
      pos: 0,
      single: true
    };
  },
  created() {
    this.getDicts("technology_working_attach").then((response) => {
      this.attachOptions = response.data;
    });
  },
  watch: {
    id(newId) {
      this.list = [];
      this.total = 0;
      this.queryParams = {
        workingId: "",
        pageNum: 1,
        pageSize: 10,
      };
      if (newId == "") {
        return;
      }
      this.queryParams.workingId = newId;
      this.getList();
    },
    
  },
  methods: {
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.id);
      this.multiple = !selection.length;
      this.single = selection.length !== 1;
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$confirm("是否确认删除该附件?", "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",closeOnClickModal:false,
        type: "warning",
      })
        .then(function () {
          return technologyWorkingAttachDel(ids);
        })
        .then(() => {
          this.getList();
          this.msgSuccess("删除成功");
        });
    },
    // 计算需要合并的单元格
    getSpanData(data) {
      // 存放计算好的合并单元格的规则
      this.spanData = [];
      for (var i = 0; i < data.length; i++) {
        if (i === 0) {
          this.spanData.push(1);
          this.pos = 0;
        } else {
          // 判断当前元素与上一个元素是否相同
          if (data[i].attachType === data[i - 1].attachType) {
            this.spanData[this.pos] += 1;
            this.spanData.push(0);
          } else {
            this.spanData.push(1);
            this.pos = i;
          }
        }
      }
    },
    listSpanMethod({ row, column, rowIndex, columnIndex }) {
      if (columnIndex === 1) {
        const _row = this.spanData[rowIndex];
        const _col = _row > 0 ? 1 : 0;
        return {
          rowspan: _row,
          colspan: _col,
        };
      }
    },
    formatter(row, column) {
      return this.selectDictLabel(this.attachOptions, row.attachType);
    },
    cancel() {
      this.fileValue = [];
      this.form.attachType = "";
      this.form.remark = "";
      this.open = false;
    },
    submitForm() {
      if (this.fileValue.length == 0) {
        this.msgError("请上传附件");
        return;
      }
      this.$refs["form"].validate((valid) => {
        if (valid) {
          let arr = this.fileValue.map((item) => {
            return { url: item, name: this.getFileName(item) };
          });
          let obj = {
            workingId: this.queryParams.workingId,
            attachType: this.form.attachType,
            technologyWorkingAttach: JSON.stringify(arr),
            remark: this.form.remark,
          };

          technologyWorkingAttach(obj).then((res) => {
            this.msgSuccess("提交成功");
            this.cancel();
            this.getList();
          });
        }
      });
    },
    delFile(file) {
      var index = this.fileValue.indexOf(file.url);
      if (index > -1) {
        this.fileValue.splice(index, 1);
      }
    },
    setFile(url, name) {
      this.fileValue.push(url);
    },
    // 获取文件名称
    getFileName(name) {
      if (name.lastIndexOf("/") > -1) {
        return name.slice(name.lastIndexOf("/") + 1).toLowerCase();
      } else {
        return "";
      }
    },
    openFunc() {
      this.open = true;
      this.$nextTick(()=>{
        this.$refs.file.clearFiles()
      })
    },
    getList() {
      technologyWorkingAttachList(this.queryParams).then((response) => {
        this.list = response.rows;
        this.getSpanData(this.list);
        this.total = response.total;
        this.loading = false;
      });
    },
    // downloadFunc(row) {
    //   download(row.url, row.name, "text/plain");
    // },
  },
};
</script>

<style>
</style>